//
//  DBHomeRepayCell.swift
//  DBCA
//
//  Created by mugua on 2024/7/4.
//

import Foundation

class DBHomeRepayBgView: UICollectionViewCell {
    
    let disposeBag = DisposeBag()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(bgView)
        bgView.addSubview(tipLabel)
        bgView.addSubview(btn)
        
        bgView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalToSuperview()
        }
        
        tipLabel.snp.makeConstraints { make in
            make.left.top.equalTo(12)
            make.right.equalTo(-90)
        }
        
        btn.snp.makeConstraints { make in
            make.right.equalTo(-12)
            make.centerY.equalToSuperview()
            make.width.equalTo(68)
            make.height.equalTo(27)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    var model: DBHomeWorkinModel? {
        didSet {
            guard let model = model else {
                return
            }
                
            
            if let suitably = model.suitably {
                let att = NSMutableAttributedString(string: suitably)
                let style = NSMutableParagraphStyle()
                style.lineSpacing = 6
                att.addAttribute(.paragraphStyle, value: style, range: att.string.rangeOfAll())
                tipLabel.attributedText = att
            }
        }
    }
    
    
    private lazy var bgView: UIView = {
        let view = UIView()
        view.backgroundColor = DBHexColor("#FFF4F1")
        view.layer.cornerRadius = 2
        return view
    }()
    
    private lazy var tipLabel: UILabel = {
        let label = UILabel()
        label.textColor = DBHexColor("FD5B0C")
        label.font = DBFuturaMaxiStd_BookFont(12)
        label.text = "Pesanan Anda telah jatuh tempo, harap dilunasi sesegera mungkin."
        label.numberOfLines = 0
        return label
    }()
    
    private lazy var btn: UIButton = {
        let btn = UIButton()
        btn.clipsToBounds = true
        btn.delayTime = 1
        btn.backgroundColor = DBViewBgColor
        btn.titleLabel?.font = DBFuturaMaxiStd_BookFont(11)
        btn.setTitle("Pelunasan", for: .normal)
        btn.setTitleColor(DBHexColor("CCFF00"), for: .normal)
        btn.layer.cornerRadius = 2
        
//        btn.rx
//            .tap
//            .bind(to: buttonTap)
//            .disposed(by: disposeBag)
        return btn
    }()
}


class DBHomeRepayCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
    
    var currentIndex = 0
    
    var isRepeat = false
    
    private var timerDisposeBag = DisposeBag()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        selectionStyle = .none
        backgroundColor = .clear
        initUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initUI(){
        contentView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(10)
        }
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let modelArr = modelArr {
            if isRepeat {
                return modelArr.count*100
            } else if modelArr.count == 1 {
                return 1
            }
        }
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: DBHomeRepayBgView = collectionView.dequeueReusableCell(withReuseIdentifier: DBHomeRepayBgView.className(), for: indexPath) as! DBHomeRepayBgView

        if isRepeat {
            if let modelArr = modelArr {
                cell.model = modelArr[indexPath.item%modelArr.count]
            }
        } else {
            cell.model = modelArr?[indexPath.item]
        }
        
        return cell
    }
    
    private func setupTimer() {
        Observable<Int>.interval(.seconds(5), scheduler: MainScheduler.instance)
            .subscribe(onNext: { _ in
                
                self.currentIndex = self.currentIndex + 1
                
                if self.currentIndex  == (self.modelArr?.count ?? 0)*100 - 1 {
                    self.collectionView.scrollToItem(at: IndexPath.init(row: 0, section: 0), at: .centeredHorizontally, animated: false)
                    self.currentIndex = 0
                } else {
                    self.collectionView.scrollToItem(at: IndexPath.init(row: self.currentIndex, section: 0), at: .centeredHorizontally, animated: true)
                }
            })
            .disposed(by: timerDisposeBag)
    }
    
    private func invalidTimer() {
        timerDisposeBag = DisposeBag()
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        invalidTimer()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        setupTimer()
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollViewDidEndScrollingAnimation(scrollView)
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        self.currentIndex = Int((scrollView.contentOffset.x + DBScreenWidth * 0.5) / DBScreenWidth)
    }
    
    var modelArr: [DBHomeWorkinModel]? {
        didSet {
            if let modelArr = modelArr {
                if modelArr.count == 1 {
                    invalidTimer()
                    isRepeat = false
                } else if modelArr.count > 1 {
                    setupTimer()
                    isRepeat = true
                }
            }
            self.collectionView.reloadData()
        }
    }
    
    private lazy var collectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .horizontal
        flowLayout.minimumLineSpacing = 0
        flowLayout.itemSize = CGSize(width: DBScreenWidth, height: 68)
        let collectView = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
        collectView.dataSource = self
        collectView.delegate = self
        collectView.showsHorizontalScrollIndicator = false
        collectView.isPagingEnabled = true
        collectView.register(DBHomeRepayBgView.self, forCellWithReuseIdentifier: DBHomeRepayBgView.className())
        
        if #available(iOS 11.0, *) {
            collectView.contentInsetAdjustmentBehavior = .never
        }
        
        return collectView
    }()
    
    
}
